<template>
  <el-main class="machinery-main">
    <div class="main-container">
      <el-row :gutter="20">
        <!-- 右侧内容区 -->
        <el-col :span="24">
          <!-- 查询表单区域 -->
          <el-card class="search-card" shadow="hover">
            <el-form :inline="true" :model="queryParams" ref="queryForm" class="search-form">
              <el-form-item label="电机型号">
                <el-input 
                  v-model="queryParams.model" 
                  placeholder="请输入电机型号" 
                  clearable 
                  prefix-icon="Document"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="电机功率">
                <el-input 
                  v-model="queryParams.power" 
                  placeholder="请输入电机功率" 
                  clearable 
                  prefix-icon="Setting"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item class="search-buttons">
                <el-button type="primary" @click="handleQuery" class="search-btn" :icon="Search">
                  查询
                </el-button>
                <el-button @click="resetQuery" class="reset-btn" :icon="Refresh">
                  重置
                </el-button>
                <el-button type="success" @click="handleAdd" class="add-btn" :icon="Plus">
                  新增
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 表格区域 -->
          <el-card class="table-card" shadow="hover">
            <el-table
              v-loading="loading"
              :data="machineryList"
              border
              :height="tableHeight"
              class="data-table"
              highlight-current-row
            >
              <el-table-column type="index" label="序号" width="70" align="center"/>
              <el-table-column prop="model" label="电机型号" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="power" label="电机功率" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="pn" label="PN" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.pn">{{ scope.row.pn }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="mn" label="MN" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.mn">{{ scope.row.mn }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="nn" label="最大托盘长度" min-width="150" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.nn">{{ scope.row.nn }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="in380v" label="IN380V" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.in380v">{{ scope.row.in380v }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" fixed="right" align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button type="primary" size="small" :icon="Edit" @click="handleUpdate(scope.row)" class="edit-btn">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)" class="delete-btn">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              v-model:current-page="queryParams.current"
              v-model:page-size="queryParams.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              class="pagination"
              @size-change="getList"
              @current-change="getList"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改电机数据对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open" 
      width="700px" 
      append-to-body
      class="machinery-dialog"
    >
      <el-scrollbar height="100%" class="form-scrollbar">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="machinery-form">
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Document /></el-icon>
                <span>基本信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="电机型号" prop="model">
                  <el-input v-model="form.model" placeholder="请输入电机型号" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电机功率" prop="power">
                  <el-input v-model="form.power" placeholder="请输入电机功率" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Setting /></el-icon>
                <span>电机参数</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="PN" prop="pn">
                  <el-input-number 
                    v-model="form.pn" 
                    placeholder="请输入PN" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="MN" prop="mn">
                  <el-input-number 
                    v-model="form.mn" 
                    placeholder="请输入MN" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大托盘长度" prop="nn">
                  <el-input-number 
                    v-model="form.nn" 
                    placeholder="请输入最大托盘长度" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="IN380V" prop="in380v">
                  <el-input-number 
                    v-model="form.in380v" 
                    placeholder="请输入IN380V" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { Search, Refresh, Plus, Edit, Delete, Document, Setting } from '@element-plus/icons-vue';
import { getElectricalMachineryList, getElectricalMachineryDetail, addElectricalMachinery, updateElectricalMachinery, deleteElectricalMachinery } from '@/api/electrical/index';
import type { ElectricalMachinery, ElectricalMachineryQuery } from '@/api/electrical/type';

// 表格高度自适应
const tableHeight = ref<number>(500);
// 计算表格高度
const calcTableHeight = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 300;
  });
};

// 页面初始化
onMounted(() => {
  calcTableHeight();
  window.addEventListener('resize', calcTableHeight);
  getList();
});

// 查询参数
const queryParams = reactive<ElectricalMachineryQuery>({
  page: 1,
  limit: 10,
  current: 1,
  size: 10,
  model: '',
  power: ''
});

// 表单数据
const form = reactive<ElectricalMachinery>({
  id: undefined,
  name: '',
  specification: '',
  price: 0,
  brand: '',
  model: '',
  power: '',
  pn: undefined,
  mn: undefined,
  nn: undefined,
  in380v: undefined
});

// 表单校验规则
const rules = reactive({
  model: [{ required: true, message: '请输入电机型号', trigger: 'blur' }],
  power: [{ required: true, message: '请输入电机功率', trigger: 'blur' }]
});

// 数据列表
const machineryList = ref<ElectricalMachinery[]>([]);
// 总记录数
const total = ref<number>(0);
// 加载状态
const loading = ref<boolean>(false);
// 弹窗标题
const title = ref<string>('');
// 是否显示弹窗
const open = ref<boolean>(false);
// 表单引用
const formRef = ref<FormInstance>();

// 查询电机数据列表
const getList = () => {
  loading.value = true;
  getElectricalMachineryList(queryParams).then((res: any) => {
    machineryList.value = res.data.records || [];
    total.value = res.data.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.current = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.model = '';
  queryParams.power = '';
  handleQuery();
};

// 表单重置
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.id = undefined;
  form.model = '';
  form.power = '';
  form.pn = undefined;
  form.mn = undefined;
  form.nn = undefined;
  form.in380v = undefined;
};

// 取消按钮
const cancel = () => {
  open.value = false;
  resetForm();
};

// 新增按钮操作
const handleAdd = () => {
  resetForm();
  open.value = true;
  title.value = '添加电机数据';
};

// 修改按钮操作
const handleUpdate = (row: ElectricalMachinery) => {
  resetForm();
  const id = row.id;
  getElectricalMachineryDetail(id as number).then((res: any) => {
    Object.assign(form, res.data);
    open.value = true;
    title.value = '修改电机数据';
  });
};

// 提交表单
const submitForm = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.id) {
          updateElectricalMachinery(form).then(() => {
            ElMessage.success('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addElectricalMachinery(form).then(() => {
            ElMessage.success('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }
};

// 删除按钮操作
const handleDelete = (row: ElectricalMachinery) => {
  const id = row.id;
  ElMessageBox.confirm('确认删除该电机数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteElectricalMachinery(id as number).then(() => {
      ElMessage.success('删除成功');
      getList();
    });
  });
};
</script>

<style scoped>
.machinery-main {
  padding: 15px;
  background-color: #f5f7fa;
}

.main-container {
  min-height: calc(100vh - 110px);
}

.search-card {
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-buttons {
  margin-left: auto;
}

.table-card {
  margin-bottom: 15px;
}

.data-table {
  margin-bottom: 15px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.machinery-form {
  padding: 10px;
}

.form-card {
  margin-bottom: 15px;
}

.form-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.form-header .el-icon {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.full-width {
  width: 100%;
}

.no-data {
  color: #999;
}
</style>
